package com.bsj.power.system.config.websocket;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.bsj.power.common.config.global.TokenUser;
import com.bsj.power.common.constant.NumericalConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.yeauty.annotation.*;
import org.yeauty.pojo.Session;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author yinhao
 * @version 1.0
 * @description websocket服务端
 * @date 2024/7/15
 */
@ServerEndpoint(port = "18080", path = "/notify")
@Component
@Slf4j
public class WebServerEndpoint {

    static Map<String, SessionInfo> sessionMap = new ConcurrentHashMap<>();

    /**
     * 消息发送
     *
     * @param msg
     */
    public void sendData(String msg) {
//        log.info("websocket："+ msg + "//" + JSONObject.toJSONString(sessionMap));
        sessionMap.forEach((key, value) -> {
            log.info("webSocket本次发送数据session{}", value);
            log.info("webSocket发送数据至前端{}", msg);
            JSONObject jsonObject = JSONObject.parseObject(msg);
            Integer msgType = jsonObject.getInteger("msgType");
            //服务器异常报警只推送给管理员
            if (msgType.equals(NumericalConstants.FOUR)) {
                if (value.getRoleType().equals(NumericalConstants.ONE) || value.getRoleType().equals(NumericalConstants.TWO)) {
                    value.getSession().sendText(msg);
                }
            } else {
                value.getSession().sendText(msg);
            }
        });
    }

    /**
     * 建立连接时执行的操作
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session, @RequestParam("sessionId") String sessionId) {
        log.info("websocket is open session Power-Cookie: {}", sessionId);
        List<String> tokenList = StpUtil.searchTokenSessionId(sessionId, 0, 1000, true);
        if (tokenList.isEmpty()) {
            log.warn("无效登录信息: {}", sessionId);
            session.sendText("登录信息错误: " + sessionId);
            session.close();
            return;
        }
        SessionInfo sessionInfo = new SessionInfo();
        SaSession token = StpUtil.getTokenSessionByToken(sessionId);
        if (token != null) {
            Object loginUser = token.get("loginUser");
            if (loginUser != null) {
                TokenUser tokenUser = (TokenUser) loginUser;
                sessionInfo.setRoleType(tokenUser.getRoleType());
            }
        }
        sessionInfo.setSession(session);
        sessionMap.put(session.id().asShortText(), sessionInfo);
    }

    /**
     * 收到客户端消息时执行的操作
     *
     * @param text 接受到客户端的消息
     * @return 返回给客户端的消息
     */
    @OnMessage
    public void onMessage(Session session, String text) {
        log.info("收到一条新消息: " + text);
        session.sendText("okk");
    }

    /**
     * 连接关闭时执行的操作
     *
     * @param session
     */
    @OnClose
    public void onClose(Session session) {
        log.info("websocket is close");
        sessionMap.remove(session.id().asShortText());
    }
}
